package com.hqu.environment.interceptor;

import com.hqu.environment.annotation.IgnoreAuth;
import com.hqu.environment.constant.Constant;
import com.hqu.environment.utils.ApiException;
import com.hqu.environment.utils.ExceptionCode;
import com.hqu.environment.utils.JwtHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: interceptor:  用户token拦截器，对指定controller进行token验证
 *          主要使用是否携带@IgnoreAuth注解过滤
 * @Author: 邓勇嘉
 * @Date:2018/11/19 18:12
 * */
public class UserVerifyInterceptor extends HandlerInterceptorAdapter {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        //获取控制器的注解是否有IgnoreAuth;
        IgnoreAuth annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);
        } else {
            return true;
        }
        //如果有拦截的请求@IgnoreAuth注解，则不验证token
        if (annotation != null) {
            return true;
        }

        String token = request.getHeader(Constant.TOKEN_NAME);

        //判断token是否为空
        if (StringUtils.isBlank(token)) throw new ApiException(ExceptionCode.USER_TOKEN_EXCEPTION);
        //解析id
        Integer id= JwtHelper.verifyToken(token);
        if(id==null) throw new ApiException(ExceptionCode.USER_TOKEN_EXCEPTION);
        //将解析的id传入request中供后续控制器使用
        request.setAttribute(Constant.LOGIN_USER, id);
        return true;
    }

}
